import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style
import loginApi from '@/api/Login.js'
import Layout from '@/layout'
import EmptyLayout from '@/layout/empty'
import MultilevelMenuExample from './modules/multilevel.menu.example'
import BreadcrumbExample from './modules/breadcrumb.example'
import KeepAliveExample from './modules/keep.alive.example'
import ComponentBasicExample from './modules/component.basic.example'
import ComponentExample from './modules/component.example'
import PermissionExample from './modules/permission.example'
import MockExample from './modules/mock.example'
import VideosExample from './modules/videos.example'
import ExTernalLinkExample from './modules/external.link.example'
import UserCenter from './modules/user_center'
import PermissionManager from './modules/permission_manager'
import db from "@/util/localstorage";

Vue.use(VueRouter);

const constantRoutes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/index'),
                meta: {
                    title: store.state.settings.dashboardTitle
                }
            },
            {
                path: 'personal',
                component: EmptyLayout,
                redirect: '/personal/setting',
                meta: {
                    title: '个人中心',
                    breadcrumb: false
                },
                children: [
                    {
                        path: 'setting',
                        name: 'personalSetting',
                        component: () => import('@/views/personal/setting'),
                        meta: {
                            title: '个人设置'
                        }
                    },
                    {
                        path: 'edit/password',
                        name: 'personalEditPassword',
                        component: () => import('@/views/personal/edit.password'),
                        meta: {
                            title: '修改密码'
                        }
                    }
                ]
            },
            {
                path: 'reload',
                name: 'reload',
                component: () => import('@/views/reload')
            }
        ]
    }
];

// 当 children 不为空的主导航只有一项时，则隐藏
let asyncRoutes = [
    {
        meta: {
            title: '默认',
            icon: 'sidebar-default'
        },
        children: [
            UserCenter,
            PermissionManager
        ]
    },
    {
        meta: {
            title: '研发效能',
            icon: 'sidebar-component'
        },
        children: [
            ...VideosExample
        ]
    },
    {
        meta: {
            title: '发布平台',
            icon: 'sidebar-layout'
        },
        children: [
            MultilevelMenuExample,
            BreadcrumbExample,
            KeepAliveExample,
            ComponentBasicExample,
            ComponentExample,
            PermissionExample,
            MockExample,
        ]
    },
    {
        meta: {
            title: '团队协作',
            icon: 'sidebar-mock'
        },
        children: [
            ExTernalLinkExample
        ]
    },
    {
        meta: {
            title: '智能测试',
            icon: 'sidebar-videos'
        },
        children: [
            {
                path: 'https://hooray.gitee.io/fantastic-admin',
                name: 'externalLinkExample',
                meta: {
                    title: '官网',
                    icon: 'sidebar-external-link'
                }
            }
        ]
    }
];

const lastRoute = [{
    path: '*',
    component: () => import('@/views/404'),
    meta: {
        title: '404',
        sidebar: false
    }
}];

const router = new VueRouter({
    routes: constantRoutes
});

// 解决路由在 push/replace 了相同地址报错的问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
};

router.beforeEach(async(to, from, next) => {
    store.state.settings.enableProgress && NProgress.start();
    // 已经登录，但还没根据权限动态挂载路由
    if (store.getters['account/isLogin'] && !store.state.menu.isGenerate) {
        /**
         * 重置 matcher
         * https://blog.csdn.net/baidu_28647571/article/details/101711682
         */
        router.matcher = new VueRouter({
            routes: constantRoutes
        }).matcher;
        // 查询路由信息
        const user = db.get('USER');
        await loginApi.getExtendRouter().then((response) => {
            const res = response.data;
            console.log(response);
            asyncRoutes = [
                {
                    meta: {
                        title: '智能测试',
                        icon: 'sidebar-videos'
                    },
                    children: [
                        {
                            path: 'https://hooray.gitee.io/fantastic-admin',
                            name: 'externalLinkExample',
                            meta: {
                                title: '官网',
                                icon: 'sidebar-external-link'
                            }
                        },
                        {
                            path: 'http://www.baidu.com',
                            name: 'baiduLink',
                            meta: {
                                title: '外部IFrame',
                                icon: 'sidebar-external-link'
                            }
                        }
                    ]
                },
                {
                    meta: {
                        title: '路由测试'
                    },
                    children: [
                        // {
                        //     path: '/mock_example',
                        //     component: 'Layout',
                        //     redirect: '/mock_example/index',
                        //     name: 'mockExample',
                        //     meta: {
                        //         title: 'Mock',
                        //         icon: 'sidebar-mock',
                        //         badge: 'NEW'
                        //     },
                        //     children: [
                        //         {
                        //             path: 'index',
                        //             name: 'mockExampleIndex',
                        //             component: 'mock_example/index',
                        //             meta: {
                        //                 title: 'Mock',
                        //                 sidebar: false,
                        //                 breadcrumb: false,
                        //                 activeMenu: '/mock_example'
                        //             }
                        //         }
                        //     ]
                        // },
                        {
                            path: 'http://www.baidu.com',
                            name: 'baiduLink1',
                            meta: {
                                title: '外部IFrame',
                                icon: 'sidebar-external-link'
                            }
                        },
                        {
                            path: '/iframe/devopsbi-vue-test-uat.yspos.com/index',
                            name: 'devopsbiDashboard',
                            // component: 'mock_example/index',
                            meta: {
                                title: '研发效能首页',
                            }
                        },
                        {
                            path: 'https://hooray.gitee.io/fantastic-admin',
                            name: 'externalLinkExample11',
                            meta: {
                                title: '官网11',
                                icon: 'sidebar-external-link'
                            }
                        },
                        {
                            path: '/multilevel_menu_example',
                            component: 'Layout',
                            // redirect: '/multilevel_menu_example/page',
                            name: 'multilevelMenuExample',
                            meta: {
                                title: '多级导航',
                                icon: 'sidebar-menu'
                            },
                            children: [
                                {
                                    path: '/iframe/devopsbi-vue-test-uat.yspos.com/story/index',
                                    name: 'devopsbiDashboard222',
                                    meta: {
                                        title: '研发效能首页111',
                                    }
                                },
                                {
                                    path: 'page',
                                    name: 'multilevelMenuExample1',
                                    component: 'multilevel_menu_example/page',
                                    meta: {
                                        title: '导航1'
                                    }
                                },
                                {
                                    path: 'level2',
                                    name: 'multilevelMenuExample2',
                                    component: 'EmptyLayout',
                                    // redirect: '/multilevel_menu_example/level2/page',
                                    meta: {
                                        title: '导航2'
                                    },
                                    children: [
                                        {
                                            path: '/iframe/devopsbi-vue-test-uat.yspos.com/index',
                                            name: 'devopsbiDashboard2222',
                                            // component: 'mock_example/index',
                                            meta: {
                                                title: '研发效能首页222',
                                            }
                                        },
                                        {
                                            path: 'page',
                                            name: 'multilevelMenuExample2-1',
                                            component: 'multilevel_menu_example/level2/page',
                                            meta: {
                                                title: '导航2-1'
                                            }
                                        },
                                        {
                                            path: 'level3',
                                            name: 'multilevelMenuExample2-2',
                                            component: 'EmptyLayout',
                                            redirect: '/multilevel_menu_example/level2/level3/page1',
                                            meta: {
                                                title: '导航2-2'
                                            },
                                            children: [
                                                {
                                                    path: 'page1',
                                                    name: 'multilevelMenuExample2-2-1',
                                                    component: 'multilevel_menu_example/level2/level3/page1',
                                                    meta: {
                                                        title: '导航2-2-1'
                                                    }
                                                },
                                                {
                                                    path: 'page2',
                                                    name: 'multilevelMenuExample2-2-2',
                                                    component: 'multilevel_menu_example/level2/level3/page2',
                                                    meta: {
                                                        title: '导航2-2-2'
                                                    }
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ];
            if (!(asyncRoutes && asyncRoutes.length > 0)) {
                asyncRoutes = []
            }
            store.commit('account/setRoutes', asyncRoutes);
        });
        console.log("=======路由查询结束=======");
        const accessRoutes = await store.dispatch('menu/generateRoutes', {
            asyncRoutes,
            currentPath: to.path
        });
        router.addRoutes(accessRoutes);
        router.addRoutes(lastRoute);
        next({...to, replace: true})
    }
    if (store.state.menu.isGenerate) {
        store.commit('menu/setHeaderActived', to.path)
    }
    to.meta.title && store.commit('settings/setTitle', to.meta.title);
    if (store.getters['account/isLogin']) {
        if (to.name) {
            if (to.matched.length !== 0) {
                // 如果已登录状态下，进入登录页会强制跳转到控制台页面
                if (to.name === 'login') {
                    next({
                        name: 'dashboard',
                        replace: true
                    })
                } else if (!store.state.settings.enableDashboard && to.name === 'dashboard') {
                    // 如果未开启控制台页面，则默认进入侧边栏导航第一个模块
                    next({
                        name: store.getters['menu/sidebarRoutes'][0].name,
                        replace: true
                    })
                }
            } else {
                // 如果是通过 name 跳转，并且 name 对应的路由没有权限时，需要做这步处理，手动指向到 404 页面
                next({
                    path: '/404'
                })
            }
        }
    } else {
        if (to.name !== 'login') {
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    // 百度统计代码
    if (process.env.VUE_APP_TYPE === 'example') {
        if (window._hmt) {
            window._hmt.push(['_trackPageview', location.pathname + '#' + to.fullPath])
        }
    }
    next()
});

router.afterEach(() => {
    store.state.settings.enableProgress && NProgress.done()
});

export default router
